<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="topNav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
        <el-breadcrumb-item>
          <span v-if="code">编辑入库单</span>
          <span v-if="!code">新增入库单</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="together-content">
      <!-- 新增/编辑入库单的入库单信息 -->
      <div>
        <el-form :inline="true" label-width="auto" style="width: 100%">
          <!-- 组装费用 -->
          <el-form-item>
            <el-input v-model="mergeOrder.mergeCost" style="width: 150px; height: 1.5rem" placeholder="组装费用" />
          </el-form-item>

          <!-- 时间选择 -->
          <el-form-item label="">
            <el-form-item label="">
              <el-date-picker v-model="datePickerValue" type="date" placeholder="选择日期" size="small" style="width: 150px"
                value-format="YYYY-MM-DD" @change="handleDateChange" />
            </el-form-item>
          </el-form-item>

        </el-form>
      </div>

      <!-- 分割线 -->
      <el-divider />

      <!-- 操作按钮 -->
      <div style="margin-bottom: 15px; text-align: right">
        <el-button type="primary" size="small" @click="save">保存</el-button>
        <el-button type="success" size="small" @click="saveAndSubmit">保存并提交</el-button>
        <el-button type="info" size="small">审核</el-button>
        <el-button type="info" size="small">反审核</el-button>
      </div>

      <div style="margin-bottom: 0.5rem">
        <span style="font-size: 0.7rem;font-weight: bold;">组合件：</span>
      </div>
      <el-table :data="mergeObj" style="width: auto" border>
        <el-table-column label="组装件" width="160" align="center">
          <template #default="scope">
            <el-input readonly v-model="scope.row.goodsName" placeholder="选择组装件" style="width: 95%"
              @click="openGoodsSelect(scope.row, scope.$index)" />
          </template>
        </el-table-column>
        <!-- 规格 -->
        <el-table-column label="规格" width="140" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.specification" readonly style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 单位 -->
        <el-table-column label="单位" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.unitName" readonly style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 仓库 -->
        <el-table-column label="仓库" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.warehouseName" readonly placeholder="选择入库仓库" style="width: 95%"
              @click="openWarehouseView(scope.row, scope.$index)" />
          </template>
        </el-table-column>

        <!-- 可用库存 -->
        <el-table-column prop="availableStock" label="可用库存" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.availableStock" readonly style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 批次号（仅当 manageType === 1 时启用） -->

        <el-table-column v-if="showBatch1" prop="batchNo" label="批次号" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.batchNo" style="width: 95%" :readonly="scope.row.type != 1">
              <!-- 右侧图标：三个点（更多） -->
              <template #suffix>
                <el-icon @click.stop="openBatchDialog(scope.row, scope.$index)">
                  <MoreFilled />
                </el-icon>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <!-- 生产日期（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch1" prop="birthday" label="生产日期" width="180" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.birthday" style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 有效期（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch1" prop="expiration" label="有效期(天)" width="110" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.expiration" style="width: 95%" />
          </template>
        </el-table-column>

        <el-table-column prop="quantity" label="数量" width="160" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity" style="width: 95%" :min="1" />
          </template>
        </el-table-column>

        <el-table-column prop="unitCost" label="单位入库成本" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.unitCost" style="width: 95%" readonly />
          </template>
        </el-table-column>

        <el-table-column prop="totalCost" label="入库成本" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.totalCost" style="width: 95%" readonly />
          </template>
        </el-table-column>
        <el-table-column label="备注" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.remark" style="width: 95%" />
          </template>
        </el-table-column>

      </el-table><br />

      <div style="margin-bottom: 0.5rem">
        <span style="font-size: 0.7rem;font-weight: bold; ">子件：</span>
      </div>
      <el-table :data="detailList" style="width: 100%" border>
        <!-- 操作列 -->
        <el-table-column label="操作" width="80px" align="center" fixed="left">
          <template #default="scope">
            <!-- add -->
            <el-button link type="success" size="small" plain @click="addDetailRow(scope.row.id)"><el-icon>
                <Plus />
              </el-icon></el-button>
            <!-- del -->
            <el-button link type="danger" size="small" plain @click="removeDetailRow(scope.row.id)"><el-icon>
                <Minus />
              </el-icon></el-button>
          </template>
        </el-table-column>

        <el-table-column label="组装子件" width="140" align="center">
          <template #default="scope">
            <el-input readonly placeholder="选择组装子件" style="width: 95%" v-model="scope.row.goodsName"
              @click="openGoodsSelect(scope.row, scope.$index)" />
          </template>
        </el-table-column>

        <el-table-column label="规格" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.specification" readonly style="width: 95%" />
          </template>
        </el-table-column>

        <el-table-column prop="unit" label="单位" width="140" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.unitName" readonly style="width: 95%" />
          </template>
        </el-table-column>

        <el-table-column label="仓库" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.warehouseName" readonly placeholder="选择出库仓库" style="width: 95%"
              @click="openWarehouseView(scope.row, scope.$index)" />
          </template>
        </el-table-column>

        <el-table-column prop="availableStock" label="可用库存" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.availableStock" readonly style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 批次号（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch2" prop="batchNo" label="批次号" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.batchNo" style="width: 95%" :readonly="scope.row.type != 1">
              <!-- 右侧图标：三个点（更多） -->
              <template #suffix>
                <el-icon @click.stop="openBatchDialog(scope.row, scope.$index)">
                  <MoreFilled />
                </el-icon>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <!-- 生产日期（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch2" prop="birthday" label="生产日期" width="180" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.birthday" style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 有效期（仅当 manageType === 1 时启用） -->
        <el-table-column v-if="showBatch2" prop="expiration" label="有效期(天)" width="110" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.expiration" style="width: 95%" />
          </template>
        </el-table-column>


        <el-table-column prop="quantity" label="数量" width="160" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.quantity" :step="1" :readonly="scope.row.type === 2" style="width: 95%;"
              @click="() => handleQuantityClick(scope.row, scope.$index)">
              <!-- 在输入框内部右侧显示 SN（仅 type === 2 时） -->
              <template #suffix>
                <span style="color: green; font-size: 12px;" v-if="scope.row.type == 2">SN</span>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <el-table-column prop="unitCost" label="出库单位成本" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.unitCost" :min="1" style="width: 95%" readonly />
          </template>
        </el-table-column>

        <el-table-column prop="totalCost" label="出库成本" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.totalCost" :min="1" style="width: 95%" readonly />
          </template>
        </el-table-column>
        <el-table-column label="备注" width="160" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.remark" :min="1" style="width: 95%" />
          </template>
        </el-table-column>
      </el-table><br />

      <!-- 调拨单备注 -->
      <el-input v-model="mergeOrder.remark" style="width: 100%" type="textarea" placeholder="暂无备注信息" />

      <!--操作日志-->
      <div style="margin-bottom: 15px; text-align: right">
        <br />
        <el-button plain @click="router.push({ name: 'merge' })">历史记录</el-button>
        <el-button plain>操作日志</el-button>
      </div>

      <!--                                    dialog                                    -->

      <!-- 批次号搜索列表弹出对话框 -->
      <el-dialog v-model="batchVisible" width="60%" style="height: auto;" draggable :show-close="true">
        <!-- 调用商品的批次搜索组件 -->
        <BatchListSelect v-model="batchVisible" @confirm="onBatchSelected" :goodsName="currentRow.goodsName"
          :goodsId="currentRow.goodsId">
        </BatchListSelect>
        <br /><br />
      </el-dialog>
      <!-- 仓库搜索列表弹出对话框 -->
      <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="40%" style="height: auto;" draggable
        :show-close="true">
        <!-- 调用仓库的搜索组件 -->
        <WareHouse ref="warehouseRef"
          :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
        <br /><br />
      </el-dialog>
      <!-- 调用序列号的新增组件 -->
      <el-dialog v-model="serialVisible" width="60%" style="height: auto;" draggable :show-close="true">
        <AddSerialNumber ref="AddSerialNumberRef" :goodsName="currentRow.goodsName" :list="currentRow.serialList"
          :status="inboundOrder.status">
        </AddSerialNumber>
        <br /><br />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="serialVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmSerialSelection">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>


    <FreeGoodsSelect v-model="showSelectGoods" @confirm="handleSelectedGoods" />
  </div>
</template>

<script setup>
import { defineProps, onMounted, ref, watch, inject } from "vue";
import { useRouter } from 'vue-router'
import { ElMessage } from "element-plus";
import { formatCreatedDate, formatDate } from "@/util";
import WareHouse from '@/views/basic/WareHouse.vue'
import FreeGoodsSelect from '@/util/FreeGoodsSelect.vue'
import BatchListSelect from "../inbound/BatchListSelect.vue";

let axios = inject('axios')
let router = useRouter();
//当前选中行
let currentRow = ref(null), currentIndex = ref(null);

// 仅用于绑定 el-date-picker 的日期部分（YYYY-MM-DD）
const datePickerValue = ref(null)
let mergeOrder = ref({
  createdTime: null,
  mergeCost: '',
  status: 1, //已创建
});
let mergeObj = ref([
  {
    tag: 0, //0是组合件，1是组合子件
  }
])
let detailList = ref([]);
const showSelectGoods = ref(false)

// ========== 用户选择日期 ==========
function handleDateChange(newDateStr) {
  // newDateStr 是 YYYY-MM-DD 字符串 或 null
  mergeOrder.value.createdTime = newDateStr ? formatCreatedDate(newDateStr) : null
  console.log(mergeOrder.value.createdTime);
}

//2.点击弹出框的方法
let batchVisible = ref(false);
function openBatchDialog(row, index) {
  batchVisible.value = true;
  currentRow.value = row;
  currentIndex.value = index;
  console.log("当前选中行：", row)
}
//这例的selected就是选中的批次列表
const onBatchSelected = (selected) => {
  // 判断当前选中的是组装件还是组装子件
  if (currentRow.value.tag == 0) {
    //组装件, 只需要获取第一个batchNo即可，因为只有一个组装件
    if (selected.length > 0) {
      mergeObj.value[0].batchNo = selected[0].code
      mergeObj.value[0].birthday = selected[0].birthday;
      mergeObj.value[0].expiration = selected[0].expiration;
    }
  } else {
    if (selected.length > 0) {
      let arr = []
      for (let i = 0; i < selected.length; i++) {
        let obj = JSON.parse(JSON.stringify(currentRow.value)); //深拷贝
        obj.batchNo = selected[i].code;
        obj.birthday = selected[i].birthday;
        obj.expiration = selected[i].expiration;
        arr.push(obj);
      }
      //这里是参考精斗云中的效果，选中多个批次，则复制几份对象
      detailList.value.splice(currentIndex.value, 1, ...arr);
    }
  }

}
const openGoodsSelect = (row, index) => {
  showSelectGoods.value = true
  currentRow.value = row;
  currentIndex.value = index;
  console.log('currentRow.value:', currentRow.value);
  console.log('currentRow.value.tag:', currentRow.value?.tag);
}

let showBatch1 = ref(false), showBatch2 = ref(false);

const handleSelectedGoods = (goodsList) => {
  if (!goodsList || goodsList.length <= 0) return;

  // goodsList：对话框勾选的商品数据
  console.log("goodsList:", goodsList);
  console.log("currentRow:", currentRow.value);

  if (currentRow.value && currentRow.value.tag == 0) { //组合件，只有一个，获取数组第一个即可
    if (goodsList[0].managerType == 1) showBatch1.value = true; //此处应该是每次数组变化，就需要进行判断，改成watch -------------------------------未改------------------------------
    mergeObj.value[0] = {
      tag: 0, // 组合件类型
      goodsId: goodsList[0].id,
      goodsCode: goodsList[0].code,
      goodsName: `${goodsList[0].code} ${goodsList[0].name}`,
      unitId: goodsList[0].unitId || null,
      unitName: goodsList[0].unitName || null,
      availableStock: goodsList[0].stock || 0,
      specification: goodsList[0].specification || null,
      warehouseId: goodsList[0].warehouse || null,
      warehouseName: goodsList[0].warehouseName || null,
      batchNo: goodsList[0].type === 1 ? goodsList[0].batchNo : null,
      birthday: goodsList[0].type === 1 ? goodsList[0].birthday : null,
      expiration: goodsList[0].type === 1 ? goodsList[0].expiration : null,
      type: goodsList[0].managerType || 0,
      quantity: 1,
      unitCost: '',
      totalCost: '',
    };
    console.log('mergeObj[0]', mergeObj.value[0]);
    return;
  }
  if (goodsList.length > 0) {
    //当前行后面添加选中的的商品信息
    let arr = [];
    for (let i = 0; i < goodsList.length; i++) {
      if (goodsList[i].managerType == 1) {
        showBatch2.value = true; //此处应该是每次数组变化，就需要进行判断
      }
      let obj = {
        tag: 1, //表示这个组合子件
        goodsId: goodsList[i].id,
        goodsCode: goodsList[i].code,
        goodsName: goodsList[i].code + ' ' + goodsList[i].name,
        unitId: goodsList[i].unitId || null,
        unitName: goodsList[i].unitName || null,
        availableStock: goodsList[i].stock || 0,
        specification: goodsList[i].specification || null,
        warehouseId: goodsList[0].warehouse || null,
        warehouseName: goodsList[0].warehouseName || null,
        batchNo: goodsList[0].type === 1 ? goodsList[0].batchNo : null,
        birthday: goodsList[0].type === 1 ? goodsList[0].birthday : null,
        expiration: goodsList[0].type === 1 ? goodsList[0].expiration : null,
        type: goodsList[i].managerType || 0,
        quantity: 1, //默认
        unitCost: goodsList[0].cost,
        totalCost: goodsList[0].cost
      }
      arr[i] = obj
    }
    console.log("arr", arr);
    //当前下标往后添加选中的商品
    detailList.value.splice(currentIndex.value, 1, ...arr);
    //计算当前商品组装件成本
    calculateCosts();
  }

}
let props = defineProps(["id"]);


const addDetailRow = (index) => {
  detailList.value.splice(index + 1, 0, {});
  calculateCosts();
}
const removeDetailRow = (index) => {
  if (detailList.value.length <= 1) {
    ElMessage.warning("至少保留一条子件记录");
    return;
  }
  detailList.value.splice(index, 1);
  calculateCosts();
};




//仓库搜索选中结果
let warehouseVisible = ref(false)
const openWarehouseView = (row, index) => {
  warehouseVisible.value = true;
  currentRow.value = row;
  currentIndex.value = index;
}

let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
  if (!newVisible) {
    if (warehouseRef.value && warehouseRef.value.selectedArray.length > 0) { //这里需要加上if判断，子组件中没有选择数据时为undefined，可能用于点击仓库，但是没选择，所以导致undefined报错
      currentRow.value.warehouseId = warehouseRef.value.selectedArray[0].id
      currentRow.value.warehouseName = warehouseRef.value.selectedArray[0].name
      //获取到仓库编码，存数据库用，仓库name仅用作展示
      //用完之后清空，避免污染其他地方数据
      warehouseRef.value.clearSelected();
    }
  }
})

// ----------------------------- 序列号 -------------------------------
//2️ 点击弹出框的方法

// 弹窗控制
const serialVisible = ref(false)

function handleQuantityClick(row, index) {
  currentRow.value = row;
  currentIndex.value = index
  if (row.type === 2) {
    serialVisible.value = true;
  }
}

let AddSerialNumberRef = ref();
const confirmSerialSelection = () => {
  const validList = AddSerialNumberRef.value?.getValidSerialList();
  if (validList && validList.length > 0) {
    // 直接保存为数组
    validList.forEach(i => i.type = 0); //type = 0 入库
    currentRow.value.serialList = [...validList]; // 深拷贝
    currentRow.value.quantity = validList.length;

  } else {
    ElMessage.warning("未选择任何有效序列号");
  }
  serialVisible.value = false; // 关闭对话框
}


// ----------------------------- 组装件成本计算 -------------------------
// 添加成本计算函数
const calculateCosts = () => {
  // 计算子件总出库成本
  let totalComponentCost = 0;

  detailList.value.forEach(item => {
    if (item.goodsId && item.quantity > 0) {
      const quantity = item.quantity || 0;
      const unitCost = parseFloat(item.unitCost) || 0;
      item.totalCost = (quantity * unitCost).toFixed(2);
      totalComponentCost += quantity * unitCost;
    }
  });

  // 计算组合件成本 = 组装费用 + 子件总成本
  if (mergeObj.value[0] && mergeObj.value[0].goodsId) {
    const assemblyCost = parseFloat(mergeOrder.value.mergeCost) || 0;
    const mainQuantity = mergeObj.value[0].quantity || 1;

    const totalCost = assemblyCost + totalComponentCost;
    const unitCost = totalCost / mainQuantity;

    mergeObj.value[0].totalCost = totalCost.toFixed(2);
    mergeObj.value[0].unitCost = unitCost.toFixed(2);
  }
};

// 监听相关数据变化
watch([
  () => mergeOrder.value.mergeCost,
  () => detailList.value,
  () => mergeObj.value[0]?.quantity
], () => {
  calculateCosts();
}, { deep: true, immediate: true });






// 新增/修改前的校验
let filteredDetailList = ref(null);
const validSave = () => {
  //组装件校验
  // 0.
  if (!mergeOrder.value.mergeCost) {
    ElMessage({ message: '请输入组装费用', type: 'warning' });
    return false;
  }
  // 1. 校验组合件（mergeObj[0]）
  const mainItem = mergeObj.value[0];
  if (!mainItem.goodsId) {
    ElMessage({ message: '请选择组装件', type: 'warning' });
    return false;
  }
  if (!mainItem.warehouseId) {
    ElMessage({ message: '请选择组装件的入库仓库', type: 'warning' });
    return false;
  }
  if (mainItem.quantity <= 0) {
    ElMessage({ message: '组装件数量必须大于0', type: 'warning' });
    return false;
  }
  // 如果启用了批次管理（type == 1），校验批次号
  if (mainItem.type == 1 && !mainItem.batchNo) {
    ElMessage({ message: `组装件【${mainItem.goodsName}】的批次号不能为空`, type: 'warning' });
    return false;
  }

  //------------------------------------------------------假数据，后面商品组件完工后再去掉------------------------------------------------------
  // mergeObj.value[0]. = 0;

  // 2. 过滤并校验子件（detailList）
  filteredDetailList.value = detailList.value.filter(item => {
    return item.goodsId && item.goodsName;
  });

  if (filteredDetailList.value.length === 0) {
    ElMessage({ message: '请添加至少一个子件', type: 'warning' });
    return false;
  }

  for (let i = 0; i < filteredDetailList.value.length; i++) {
    const detail = filteredDetailList.value[i];
    if (detail.goodsId == mainItem.goodsId) {
      ElMessage({ message: '组装子件不能和组装件一致', type: "warning" })
      return;
    }

    // 校验出库仓库
    if (!detail.warehouseId || !detail.warehouseName) {
      ElMessage({ message: `请选择子件【${detail.goodsName}】的出库仓库`, type: 'warning' });
      return false;
    }

    // 校验数量
    if (detail.quantity <= 0) {
      ElMessage({ message: `子件【${detail.goodsName}】的数量必须大于0`, type: 'warning' });
      return false;
    }

    // 批次号校验（如果启用了批次管理）
    if (detail.type === 1 && !detail.batchNo) {
      ElMessage({ message: `子件【${detail.goodsName}】的批次号不能为空`, type: 'warning' });
      return false;
    }
  }

  return true;
};


const save = () => {
  if (props.id || mergeOrder.value.id) {
    console.log("修改组装单");
    if (validSave()) {
      modify();
    }
  } else {
    console.log("新增组装单");
    if (validSave()) {
      add();
    }
  }
};

const saveAndSubmit = () => {
  mergeOrder.value.status = 2; // 假设 2 表示“已提交”
  save();
};


let originalDetailList = ref(null); // 原始子件列表
let originalMergeOrder = ref(null); // 原始主单（含组合件信息）
let originalOrder = ref(null);   // 原始组合件（可选，用于对比）

const modify = async () => {
  // 1. 构建原始子件 ID 映射
  const originalMap = new Map(
    originalDetailList.value.map(item => [item.id, item])
  );

  // 2. 分离新增、修改、删除的子件
  let addList = [], modList = [], delList = [];

  filteredDetailList.value.forEach(current => {
    if (!current.id) {
      addList.push(current);
    } else {
      const original = originalMap.get(current.id);
      if (original && hasModifiedDetail(current, original)) {
        modList.push(current);
      }
      originalMap.delete(current.id); // 标记为已处理
    }
  });

  // 3. 剩余的就是被删除的
  for (const id of originalMap.keys()) {
    delList.push(id);
  }

  // 4. 判断主单（含组合件）是否修改
  const mainItem = mergeObj.value[0];
  const orderModified = hasModifiedOrder(originalMergeOrder.value, mergeOrder.value);
  const mainItemModified = hasModifiedDetail(originalOrder.value, mainItem);

  try {
    const rs = await axios({
      url: '/xyy/merge/modify', // ← 替换为你的实际接口
      method: 'post',
      data: {
        orderModified: orderModified || mainItemModified,
        mainItem: mainItem, // 组合件数据
        addList: addList,
        modList: modList,
        delList: delList,
        merge: mergeOrder.value // 主单信息（如 remark, createdTime, status 等）
      }
    });

    if (rs.data.code === 5200) {
      ElMessage({ message: "修改组装单成功", type: 'success' });
      router.push({ name: 'merge' }); // 跳转到组装单列表页
      return;
    }
    ElMessage({ message: rs.data.msg || "修改组装单失败", type: 'error' });
  } catch (error) {
    console.error('修改组装单异常:', error);
    ElMessage({ message: `修改异常: ${error.message}`, type: 'error' });
  }
};

const add = async () => {
  // 校验已在 validSave 中完成，此处直接提交
  try {
    const rs = await axios({
      url: '/xyy/merge/create', // ← 替换为你的实际接口
      method: 'post',
      data: {
        goodsMerge: mergeOrder.value,
        detailList: [...filteredDetailList.value, mergeObj.value[0]] // 子件列表
      }
    });

    if (rs.data.code === 5200) {
      ElMessage({ message: '新增组装单成功！', type: 'success' });
      router.push({ name: 'merge' });
      return;
    } else {
      ElMessage({ message: rs.data.msg || '新增组装单失败！', type: 'error' });
    }
  } catch (error) {
    console.error('新增组装单异常:', error);
    ElMessage({ message: `新增异常: ${error.message}`, type: 'error' });
  }
};


function hasModifiedOrder(current, original) {
  const fields = ["createdTime", "remark", "status", "mergeCost"];
  return fields.some(field => {
    const curr = current?.[field] ?? '';
    const orig = original?.[field] ?? '';
    return curr !== orig;
  });
}

function hasModifiedDetail(current, original) {
  if (!original) return true;
  const fields = [
    "goodsId",
    "warehouseId",
    "quantity",
    "batchNo",

  ];
  return fields.some(field => {
    const curr = current?.[field] ?? '';
    const orig = original?.[field] ?? '';
    return curr !== orig;
  });
}

onMounted(() => {
  init();
})

const init = async () => {
  if (props.id) {
    const rs = await axios({
      url: `/xyy/merge/get/${props.id}`,
      method: 'post',
    });
    if (rs.data.code == 5200) {
      const data = rs.data.mergeRequest;
      const list = rs.data.mergeRequest.detailList;

      console.log("list", list);
      // 主单
      mergeOrder.value = { ...data.goodsMerge };
      originalMergeOrder.value = { ...data.goodsMerge };

      // 组合件
      mergeObj.value = list.filter(i => i.tag == 0);
      originalOrder.value = list.filter(i => i.tag == 0);

      // 子件明细
      detailList.value = list.filter(i => i.tag == 1);
      originalDetailList.value = list.filter(i => i.tag == 1);

      // 日期初始化
      datePickerValue.value = mergeOrder.value.createdTime?.substring(0, 10) || formatDate(new Date());
    }
  } else {
    detailList.value = [{}];
    //组装单创建时间初始化
    mergeOrder.value.createdTime = formatDate(new Date());
    datePickerValue.value = mergeOrder.value.createdTime.substring(0, 10)
  }
};

</script>

<style></style>